package com.rabbiter.oes.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.rabbiter.oes.entity.Student;
import com.rabbiter.oes.enums.RoleEnum;
import com.rabbiter.oes.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@Controller
public class BaseController {

    @Autowired
    private StudentService studentService;

    /**
     * 获取登陆用户身份
     *
     * @param request
     * @return
     */
    public RoleEnum getRole(HttpServletRequest request) {
        if (request.getCookies() == null) {
            return RoleEnum.UNKNOWN;
        }
        for (Cookie cookie : request.getCookies()) {
            if ("rb_role".equals(cookie.getName())) {
                Integer code = Integer.valueOf(cookie.getValue());
                return RoleEnum.getRoleEnum(code);
            }
        }
        return RoleEnum.UNKNOWN;
    }

    /**
     * 获取当前登陆学生信息
     * @param request
     * @return
     */
    public Student getLoginStudent(HttpServletRequest request) {
        if (request.getCookies() == null) {
            throw new IllegalArgumentException("请先完成登陆");
        }
        for (Cookie cookie : request.getCookies()) {
            if ("cid".equals(cookie.getName())) {
                Integer id = Integer.valueOf(cookie.getValue());
                Student student = studentService.findById(id);
                Assert.isTrue(ObjectUtil.isNotEmpty(student), "登陆用户信息未获取到");
                return student;
            }
        }
        throw new IllegalArgumentException("未获取到登陆成功用户信息。");
    }

}
